<template>
  <div class="insert-page">
    <el-form :model="formData" label-width="100px">
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-row>
            <el-col :span="5">
              <el-form-item label="名称" required>
                <el-input placeholder="请输入名称" v-model="formData.name"></el-input>
                <span v-if="nameError" style="color: red;" class="error-message">{{ nameError }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="规格">
                <el-input placeholder="请输入规格" v-model="formData.standard"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item label="型号">
                <el-input placeholder="请输入型号" v-model="formData.model"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="9">
              <el-row :gutter="20"> <!-- 控制列之间的间距 -->
                <el-col :span="20"> <!-- 20个栅格 -->
                  <el-form-item label="单位" required>
                    <template  v-if="formData.multiUnit">
                      <el-select v-model="formData.unitId" placeholder="请选择单位" @change="handleUnitChange">
                        <el-option v-for="item in da" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                    </template>
                    <template v-else>
                      <el-input placeholder="请输入单位" v-model="formData.unit" @input="updateUnits"></el-input>
                    </template>
                    <span v-if="unitError" style="color: red;" class="error-message">{{ unitError }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="4" style="margin-bottom: 30px;">
                  <el-checkbox v-model="formData.multiUnit"     @change="handleMultiUnitChange">多单位</el-checkbox>
                </el-col>
              </el-row>
             
            </el-col>

            <el-col :span="6">
              <el-form-item label="颜色">
                <el-input placeholder="请输入颜色" v-model="formData.color"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="基础重量">
                <el-input-number v-model="formData.weight" :min="0" placeholder="请输入基础重量(kg)"
                  controls-position="right" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="保质期">
                <el-input-number v-model="formData.expiryNum" :min="0" placeholder="请输入保质期(天)"
                  controls-position="right" />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="类别:">
                <el-tree-select v-model="formData.categoryId"
                  :props="{ value: 'id', label: 'name', children: 'children' }" :data="organTreeData"
                  :render-after-expand="false" check-strictly clearable />
              </el-form-item>
            </el-col>

            <!-- <el-col :span="6">
              <el-form-item label="序列号">
                <el-select v-model="formData.enableSerialNumber">
                  <el-option label="有" :value="1"></el-option>
                  <el-option label="无" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item label="序列号">
                <el-select v-model="formData.enableSerialNumber">
                  <el-option v-for="option in serialOptions" :key="option.value" :label="option.label"
                    :value="option.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="批号">
                <el-select v-model="formData.enableBatchNumber">
                  <el-option label="有" :value="1"></el-option>
                  <el-option label="无" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="仓位货架">
                <el-input placeholder="请输入仓位货架" v-model="formData.position"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="多属性">
                <!-- <el-input placeholder="需现录入单位才能激活" v-model="formData.position"></el-input> -->

                <el-select v-model="value1" multiple placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>

              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>插入行</span>
            </el-button>
            <el-button type="primary" @click="removeSelectedRows" class="ant-btn ant-btn-danger"
              v-if="selectedRows.length > 0">
              <el-icon class="el-icon-left">
                <Minus />
              </el-icon>
              <span>移除行</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>采购价-批量</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>零售价-批量</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>销售价-批量</span>
            </el-button>
            <el-button class="ant-btn ant-btn-primary">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>
              <span>最低售价-批量</span>
            </el-button>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-table :data="tableData" @selection-change="handleSelectionChange"
                style="width: 100%; margin-top: 10px; border: 1px solid #e0e0e0; border-collapse: collapse;">
                <el-table-column type="selection" width="55" />
                <el-table-column label="条码" width="120">
                  <template #default="{ row }">
                    <el-input v-model="row.barcode"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.unit" placeholder="请输入单位"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="采购价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.purchaseDecimal" placeholder="请输入采购价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="零售价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.commodityDecimal" placeholder="请输入零售价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="销售价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.wholesaleDecimal" placeholder="请输入销售价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="最低售价" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.lowDecimal" placeholder="请输入最低售价"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="商品最低库存" width="150">
                  <template #default="{ row }">
                    <el-input v-model="row.erpMaterialExtend.initialInventory" placeholder="请输入商品初始库存"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>

            <el-col :span="24" style="padding: 0;">
              <el-form-item style="margin-top: 5px; width: 100%;">
                <el-input :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" placeholder="请输入备注"
                v-model="formData.remark" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="扩展信息">
          <div style="width: 25%;" margin-top="500px">
            <div>
              <el-form-item label="制造商">
                <el-input v-model="formData.mfrs"></el-input>
              </el-form-item>
            </div>
            <div></div>
            <el-form-item label="自定义1">
              <el-input v-model="formData.otherField1"></el-input>
            </el-form-item>

            <el-form-item label="自定义2">
              <el-input v-model="formData.otherField2"></el-input>
            </el-form-item>

            <el-form-item label="自定义3">
              <el-input v-model="formData.otherField3"></el-input>
            </el-form-item>
          </div>
        </el-tab-pane>

       
      </el-tabs>

      <el-row style="margin-top: 200px; border-top: #e0e0e0 1px solid;">
        <el-col :span="24" :offset="0" style="margin-top: 10px;">
          <el-form-item style="float: right">
            <el-button @click="close">关 闭</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, defineEmits, onMounted, defineProps, computed } from 'vue';
import reqeust from '@/api/request';
import router from '@/router';
import { Plus, Minus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 接收传入的 props
const props = defineProps(['data']);
let emits = defineEmits(['close']);
let close = () => {
  emits('close');
};
const productId = props.data.id; // 假设路由中传入了商品ID

console.log("props:", props.data.id);
let formData = ref({
  name: '',
  standard: '',
  model: '',
  unit: '',
  unitId: null,
  color: '',
  weight: '',
  expiryNum: '',
  position: '',
  remark: '',
  enableSerialNumber: 0,
  enableBatchNumber: 0,
  categoryId: null,
  mfrs: '',
  otherField1: '',
  otherField2: '',
  otherField3: '',
  warehouse: '',
  initialStock: 0,
});

// Table 数据
const tableData = ref([]);

// 更新表格中每一行的单位值
const updateUnits = () => {
  tableData.value.forEach(row => {
    row.unit = formData.value.unit; // 将表单中的单位同步给每一行
  });
};

const da = ref([]);

// 查询多单位
let findsuppliers = () => {
  reqeust({
    url: '/commodity/unit/list',
    method: 'get'
  }).then(resp => {
    da.value = resp.data;
  });
};
findsuppliers();

// 添加一行
const addRow = () => {
  tableData.value.push({
    barcode: '',
    unit: '',
    erpMaterialExtend: {
      purchaseDecimal: '',
      commodityDecimal: '',
      wholesaleDecimal: '',
      lowDecimal: ''
    }
  });
};

// 切换复选框状态时的处理
const handleMultiUnitChange = (checked) => {
  if (!checked) {
    formData.value.unitId = null; // 如果取消多单位，清空 unitId
    formData.value.unit = ''; // 清空输入框
  } else {
    // 如果勾选了多单位，确保输入的单位不会影响选项
    if (formData.value.unit) {
      formData.value.unit = ''; // 清空输入框
    }
  }
};


const serialOptions = ref([
  { label: "有", value: 1 },
  { label: "无", value: 0 }
]);



const onSubmit = () => {
  const requestData = {
    material: {
      ...formData.value
      // 添加额外的字段，如 tenantId，这通常在后端处理
    },
    materialExtends: tableData.value.map(row => ({
      barCode: row.barcode,
      commodityUnit: row.unit,
      initialInventory: row.erpMaterialExtend.initialInventory, // 商品初始库存，暂时设置为 0
      purchaseDecimal: row.erpMaterialExtend.purchaseDecimal,
      commodityDecimal: row.erpMaterialExtend.commodityDecimal,
      wholesaleDecimal: row.erpMaterialExtend.wholesaleDecimal,
      lowDecimal: row.erpMaterialExtend.lowDecimal
    
    }))
  };

  console.log("提交表单数据:", requestData);

  reqeust.put(`/commodity/material/update`, requestData, {
    headers: {
      'Content-Type': 'application/json',
    },
  }).then(resp => {
    if (resp.code === 200) {
      ElMessage.success('修改成功');
      router.push("/commodity/material");
      emits('close');
    }
  }).catch(error => {
    console.error('出错了', error);
    ElMessage.error('修改失败');
  });
};
// 加载类别数据
const organTreeData = ref([]);
const findOrgan = () => {
  reqeust.get('cam/findOrganTree').then(resp => {
    if (resp.code == 200) {
      organTreeData.value = resp.data;
    }
  });
};
// 声明一个响应式变量，存储选择的数据
const selectedData = ref(null);
// 选中的行
const selectedRows = ref([]);
const handleSelectionChange = (selected) => {
  selectedRows.value = selected;
};

// 移除选中的行
const removeSelectedRows = () => {
  const selectedBarcodes = selectedRows.value.map(row => row.barcode);
  tableData.value = tableData.value.filter(row => !selectedBarcodes.includes(row.barcode));
  selectedRows.value = []; // 清空选中的行
};

// 定义 handleUnitChange 函数
let handleUnitChange = (value) => {
  console.log('选中的单位ID:', value);

  reqeust.get('/commodity/unit/select/' + value)
    .then(response => {
      if (response.data) {
        console.log('返回的数据:', response.data);
        selectedData.value = response.data; // 将返回的数据存储在 selectedData 中
        console.log("选中的单位", selectedData.value);
        // 获取 basicUnit 的值
        const basicUnit = selectedData.value[0].basicUnit;
        console.log("基本单位", basicUnit);
        tableData.value.forEach(row => {
          row.unit = basicUnit; // 将单位值同步给每一行
        });
      }
    })
    .catch(error => {
      console.error('请求失败:', error);
    });
};

// 填充表格数据的函数
const fetchMaterialExtends = async (id) => {
  try {
    const response = await reqeust.get(`/commodity/material/selectByMaterialId?id=${id}`);
    if (response.code === 200) {
      // 将获取的扩展信息填充到 tableData 中
      tableData.value = response.data.map(item => ({
        barcode: item.barCode,
        unit: item.commodityUnit,
        erpMaterialExtend: {
          initialInventory: item.initialInventory, // 商品初始库存，暂时设置为 0
          purchaseDecimal: item.purchaseDecimal,
          commodityDecimal: item.commodityDecimal,
          wholesaleDecimal: item.wholesaleDecimal,
          lowDecimal: item.lowDecimal,
        },
        erpUnit: {
          basicUnit: item.basicUnit // 如果有基础单位的话
        }
      }));
    } else {
      ElMessage.error('获取扩展信息失败');
    }
  } catch (error) {
    console.error('出错了', error);
    ElMessage.error('请求扩展信息失败');
  }
};


// 初始化时，将传入的数据设置到表单中
onMounted(() => {
  if (props.data) {
    console.log('effect', props.data)
    // 填充表单数据
    formData.value = {
      ...props.data, // 直接展开 props.data
      // 确保其他未定义的字段有默认值
      weight: props.data.weight || 0,
      expiryNum: props.data.expiryNum || 0,
      initialStock: props.data.initialStock || 0,
    };
  

    // 获取扩展信息
    if (productId) {
      fetchMaterialExtends(productId);
    }
  }
  formData.value.multiUnit = !!formData.value.unitId; // 如果 unitId 有值则复选框选中
});

findOrgan();
</script>

<style scoped>
.el-tabs {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-table {
  width: 100%;
  border: 1px solid #e0e0e0;
}

.el-table th,
.el-table td {
  border: none;
}

.el-table tr {
  border-bottom: 1px solid #e0e0e0;
}
</style>
